package com.btkjgc.utils;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class PdfReportTableUtil
{
	private BaseFont basefont;
	private String pdfFileName;
	private String titile;
	private String[] tableHeaders;
	private HttpServletResponse response;
	private List<List<String>> content;
	private PdfPTable table;

	public PdfReportTableUtil(String pdfFileName, String titile,
			String[] tableHeaders, List<List<String>> content,
			HttpServletResponse response)
	{
		this.pdfFileName = pdfFileName;
		this.titile = titile;
		this.tableHeaders = tableHeaders;
		this.response = response;
		this.content = content;
		init();
	}

	@SuppressWarnings("static-access")
	private void init()
	{
		try
		{
			// step 1
			Document document = new Document();
			// step 2
			String fileName = java.net.URLEncoder.encode(pdfFileName, "UTF-8");
			response.setContentType("application/pdf");
			response.setHeader("Content-disposition", "attachment;filename="
					+ fileName + ".pdf");
			PdfWriter.getInstance(document, response.getOutputStream());
			// step 3
			document.open();
			// step 4
			basefont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
					BaseFont.NOT_EMBEDDED);
			Paragraph titleP = new Paragraph(titile + "\n\n", getFont(18));
			titleP.setAlignment(titleP.ALIGN_CENTER);
			document.add(titleP);
			table = new PdfPTable(tableHeaders.length);
			table.setHeaderRows(1);
			setTableHeader();
			fillTable();
			document.add(table);
			// step 5
			document.close();
		}
		catch (DocumentException e)
		{
			e.printStackTrace();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public Font getFont(float size)
	{
		return new Font(basefont, size, Font.NORMAL);
	}

	public void setTableHeader()
	{
		for (String h : tableHeaders)
		{
			Paragraph p = new Paragraph(h, getFont(9));
			PdfPCell pc = new PdfPCell(p);
			pc.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(pc);
		}
	}

	public void fillTable()
	{
		for (List<String> row : content)
		{
			for (String c : row)
			{
				Paragraph p = new Paragraph(c, getFont(9));
				PdfPCell pc = new PdfPCell(p);
				pc.setHorizontalAlignment(Element.ALIGN_CENTER);
				table.addCell(pc);
			}
		}
	}
}
